package com.efoundercalendar.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.ospmobilelib.R;
import com.efoundercalendar.adapter.EventListAdapter;
import com.efoundercalendar.database.EventDBHelper;
import com.efoundercalendar.entity.EventBean;
import com.efoundercalendar.view.CustomDayView;
import com.ldf.calendar.Utils;
import com.ldf.calendar.component.CalendarAttr;
import com.ldf.calendar.component.CalendarViewAdapter;
import com.ldf.calendar.interf.OnSelectDateListener;
import com.ldf.calendar.model.CalendarDate;
import com.ldf.calendar.view.Calendar;
import com.ldf.calendar.view.MonthPager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class CalendarMonthActivity extends AppCompatActivity {

    TextView textViewYearDisplay;
    TextView textViewMonthDisplay;
    RecyclerView rvToDoList;
    TextView backToday;
    FloatingActionButton addEvent;
    CoordinatorLayout content;
    MonthPager monthPager;

    EventListAdapter mEventListAdapter;
    //数据库帮助类
    private EventDBHelper mDBHelper;

    private List<Calendar> currentCalendars = new ArrayList<>();
    //从数据库中读取的日程信息
    private List<EventBean> mEventBeanList = new ArrayList<EventBean>();
    //获取有日程信息的标记日期
    HashMap<String, String> markData = new HashMap<>();
    private CalendarViewAdapter calendarAdapter;
    private OnSelectDateListener onSelectDateListener;
    private int mCurrentPage = MonthPager.CURRENT_DAY_INDEX;
    private Context context;
    private CalendarDate currentDate;
    private boolean initiated = false;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    bindData();
                    break;
                case 2:
                    calendarAdapter.setMarkData(markData);
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar_month);

        mDBHelper = new EventDBHelper(getApplicationContext());

        context = this;
        content = (CoordinatorLayout) findViewById(R.id.content);
        monthPager = (MonthPager) findViewById(R.id.calendar_view);
        //此处强行setViewHeight，毕竟你知道你的日历牌的高度
        monthPager.setViewheight(Utils.dpi2px(context, 270));
        textViewYearDisplay = (TextView) findViewById(R.id.show_year_view);
        textViewMonthDisplay = (TextView) findViewById(R.id.show_month_view);

        initToolBar();
        rvToDoList = (RecyclerView) findViewById(R.id.list);
        rvToDoList.setHasFixedSize(true);
//        这里用线性显示 类似于listview
        rvToDoList.setLayoutManager(new LinearLayoutManager(this));


        initAddButton();

        initCurrentDate();
        initCalendarView();

        getEventData(currentDate);

    }

    @Override
    protected void onResume() {
        super.onResume();
        initMarkData();
        getEventData(currentDate);

    }

    /**
     * onWindowFocusChanged回调时，将当前月的种子日期修改为今天
     *
     * @return void
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && !initiated) {
            refreshMonthPager();
            initiated = true;
        }
    }

    private void initAddButton(){
        addEvent = (FloatingActionButton)findViewById(R.id.add_event);
        addEvent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CalendarMonthActivity.this,AddScheduleActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 顶部view
     */
    private void initToolBar() {
        LinearLayout leftbacklayout = (LinearLayout) findViewById(R.id.leftbacklayout);
        leftbacklayout.setVisibility(View.VISIBLE);
        leftbacklayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView meetingDate = (TextView) findViewById(R.id.meeting_date);
        meetingDate.setVisibility(View.INVISIBLE);
//        meetingDate.setText("");
////        meetingDate.setBackgroundResource(R.mipmap.icon_change);
//        meetingDate.setTextColor(this.getResources().getColor(R.color.white));
//        meetingDate.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                //详情
//                Intent i = new Intent(CalendarMonthActivity.this, CalendarDayActivity.class);
//                startActivity(i);
//            }
//        });
//        meetingDate.setVisibility(View.VISIBLE);

        Button change = (Button)findViewById(R.id.closeButton);
        change.setVisibility(View.VISIBLE);
        change.setBackgroundResource(R.mipmap.icon_change);
        change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开带时间轴视图的activity
                Intent i = new Intent(CalendarMonthActivity.this, CalendarDayActivity.class);
                startActivity(i);
            }
        });

        TextView title = (TextView) findViewById(R.id.fragmenttitle);
        title.setText("日历");
        title.setTextColor(Color.WHITE);
    }

    /**
     * 初始化currentDate
     *
     * @return void
     */
    private void initCurrentDate() {
        currentDate = new CalendarDate();
        textViewYearDisplay.setText(currentDate.getYear() + "年");
        textViewMonthDisplay.setText(currentDate.getMonth() + "");
    }

    /**
     * 初始化CustomDayView，并作为CalendarViewAdapter的参数传入
     *
     * @return void
     */
    private void initCalendarView() {
        initListener();
        CustomDayView customDayView = new CustomDayView(context, R.layout.custom_day);
        calendarAdapter = new CalendarViewAdapter(
                context,
                onSelectDateListener,
                CalendarAttr.CalendayType.MONTH,
                customDayView);
        initMarkData();
        initMonthPager();
    }

    /**
     * 初始化标记数据，HashMap的形式，可自定义
     *
     * @return void
     */
    private void initMarkData() {
//        HashMap<String, String> markData = new HashMap<>();
//        markData.put("2017-8-9", "1");
//        markData.put("2017-7-9", "0");
//        markData.put("2017-6-9", "1");
//        markData.put("2017-6-10", "0");
//        calendarAdapter.setMarkData(markData);
        new Thread(new Runnable() {
            @Override
            public void run() {
                markData = mDBHelper.getMarkDay();
                Message message = new Message();
                message.what = 2;
                mHandler.sendMessage(message);
            }
        }).start();
    }

    private void initListener() {
        onSelectDateListener = new OnSelectDateListener() {

            @Override
            public void onLongSelectDate(CalendarDate date) {
//                startActivity(new Intent(CalendarMonthActivity.this, CalendarDayActivity.class));
                Log.i("日历","长按事件"+date);
            }

            @Override
            public void onSelectDate(CalendarDate date) {
                refreshClickDate(date);
                //todo 选择日期后更新日历下面的日程列表
            }

            @Override
            public void onSelectOtherMonth(int offset) {
                //偏移量 -1表示刷新成上一个月数据 ， 1表示刷新成下一个月数据
                monthPager.selectOtherMonth(offset);
            }
        };
    }

    private void refreshClickDate(CalendarDate date) {
        currentDate = date;
        getEventData(currentDate);
        textViewYearDisplay.setText(date.getYear() + "年");
        textViewMonthDisplay.setText(date.getMonth() + "");
    }

    /**
     * 初始化monthPager，MonthPager继承自ViewPager
     *
     * @return void
     */
    private void initMonthPager() {
        monthPager.setAdapter(calendarAdapter);
        monthPager.setCurrentItem(MonthPager.CURRENT_DAY_INDEX);
        monthPager.setPageTransformer(false, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                position = (float) Math.sqrt(1 - Math.abs(position));
                page.setAlpha(position);
            }
        });
        monthPager.addOnPageChangeListener(new MonthPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mCurrentPage = position;
                currentCalendars = calendarAdapter.getPagers();
                if (currentCalendars.get(position % currentCalendars.size()) instanceof Calendar) {
                    CalendarDate date = currentCalendars.get(position % currentCalendars.size()).getSeedDate();
                    currentDate = date;
                    textViewYearDisplay.setText(date.getYear() + "年");
                    textViewMonthDisplay.setText(date.getMonth() + "");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    public void onClickBackToDayBtn() {
        refreshMonthPager();
    }

    private void refreshMonthPager() {
        CalendarDate today = new CalendarDate();
        getEventData(today);
        calendarAdapter.notifyDataChanged(today);
        textViewYearDisplay.setText(today.getYear() + "年");
        textViewMonthDisplay.setText(today.getMonth() + "");
    }

    //根据日期获取日程信息列表
    private void getEventData(final CalendarDate calendarDate){
        new Thread(new Runnable() {
            @Override
            public void run() {
                mEventBeanList = mDBHelper.getEventByDay(calendarDate);
                Message message = new Message();
                message.what = 1;
                mHandler.sendMessage(message);
            }
        }).start();
    }

    private void bindData(){
        mEventListAdapter = new EventListAdapter(CalendarMonthActivity.this, mEventBeanList);
        rvToDoList.setAdapter(mEventListAdapter);
    }

}
